#include "World.h"
#include "MathUtility.h"
#include "MyGL.h"

World::World(){}

void World::CreateRandom(unsigned int width, unsigned int height,
						 float cellWidth, float cellHeight,
						 unsigned int percentageOfObstacles)
{
	m_cellDims.x = cellWidth;
	m_cellDims.y = cellHeight;

	m_cellGrid = CellGrid(width, std::vector <bool> (height, true));

	int percentageInt = (int)percentageOfObstacles;
	int rand = 0;
	unsigned int ctr = 0;

	m_offset.x = (m_cellDims.x * (float)width) * .5f;
	m_offset.y = (m_cellDims.y * (float)height) * .5f;

	Engine::Vec3 temp, temp2;

	for(unsigned int y = 0; y < height; ++y)
		for(unsigned int x = 0; x < width; ++x)
		{
			rand = Engine::Random(100);

			if(rand > percentageInt) continue;

			m_cellGrid[x][y] = false;

			m_obstacleVec.push_back(new Obstacle());

			temp.x = (m_cellDims.x * (float)x) - m_offset.x;
			temp.z = (m_cellDims.y * (float)y) - m_offset.y;

			temp2.x = temp.x + m_cellDims.x;
			temp2.z = temp.z + m_cellDims.y;

			m_obstacleVec[ctr] ->SetAABB(Engine::AABB(temp, temp2));

			temp.x += (m_cellDims.x * .5f);
			temp.z += (m_cellDims.y * .5f);

			m_obstacleVec[ctr] ->SetPos(temp);
			
			m_obstacleVec[ctr] ->Initialize();

			++ctr;
		}
}

void World::Draw()
{ 
	glPushMatrix();
		glBegin(GL_LINES);
			glColor3f(1.0f, 1.0f, 1.0f);
			
			//horizontal lines
			for(unsigned int y = 0; y < m_cellGrid[0].size() + 1; ++y)
			{
				glVertex3f(-m_offset.x, 0.0f, (m_cellDims.y * (float)y) - m_offset.y);
				glVertex3f(m_offset.x, 0.0f, (m_cellDims.y * (float)y) - m_offset.y);
			}

			//vertical lines
			for(unsigned int x = 0; x < m_cellGrid.size() + 1; ++x)
			{
				glVertex3f((m_cellDims.x * (float)x) - m_offset.x, 0.0f, -m_offset.y);
				glVertex3f((m_cellDims.x * (float)x) - m_offset.x, 0.0f, m_offset.y);
			}
		glEnd();
	glPopMatrix();
}

bool World::IsBoundary(unsigned int x, unsigned int y)
{
	if(x < 0 || x >= m_cellGrid.size() ||	y < 0 || y >= m_cellGrid[0].size())
		return false;
	
	return true;
}

bool World::IsPassable(unsigned int x, unsigned int y)
{
	return m_cellGrid[x][y];
}

World::~World()
{
	unsigned int s = m_obstacleVec.size();
	for(unsigned int n = 0; n < s; ++n)
		delete m_obstacleVec[n];
}
